import { Injectable } from '@nestjs/common';
import { LoggerService } from '../logger/logger.service';
import { PrismaService } from '../prisma/prisma.service';
import { RedisKeyEnum } from '../enums/redis-key.enum';
import { ExtraInfoDto } from './dto/extra-info.dto';
import { Cacheable, CacheEvict } from '../decorators/cache.decorator';
import { handleError } from '@/utils/handle.error';

@Injectable()
export class AccountService {

  constructor(
    private readonly logger: LoggerService,
    private readonly prismaService: PrismaService
  ) {
    this.logger.setContext(AccountService.name);
  }

  /** 存储信息字段 */
  @CacheEvict(RedisKeyEnum.ExtraInfoKey)
  async setExtraInfo(extraInfo: ExtraInfoDto) {
    try {
      this.logger.log(`${this.setExtraInfo.name} was called`);

      const findExtraInfo = await this.prismaService.account.findFirst({
        where: {
          miniAppid: extraInfo.miniAppid,
          miniSecret: extraInfo.miniSecret,
          miniToken: extraInfo.miniToken,
          miniEncodingAESKey: extraInfo.miniEncodingAESKey,
          feishuAppid: extraInfo.feishuAppid,
          feishuSecret: extraInfo.feishuSecret,
          spreadsheetToken: extraInfo.spreadsheetToken,
          sheetName: extraInfo.sheetName,
          miniTemplateId: extraInfo.miniTemplateId,
        }
      })

      // 先将其他isDelete设为true
      await this.prismaService.account.updateMany({
        where: {
          isDelete: false,
        },
        data: {
          isDelete: true
        }
      })

      if (findExtraInfo) {
        await this.prismaService.account.update({
          where: {
            id: findExtraInfo.id
          },
          data: {
            isDelete: false
          }
        })
        return '信息已存在'
      }

      const { id } = await this.prismaService.account.create({
        data: { ...extraInfo, isDelete: false },
        select: {
          id: true,
        },
      })
      return id
    } catch (error) {
      handleError(this.logger, error, {
        common: '存储信息字段失败'
      })
    }
  }

  /** 存储信息字段 */
  @Cacheable(RedisKeyEnum.ExtraInfoKey)
  async getExtraInfo() {
    try {
      this.logger.log(`${this.getExtraInfo.name} was called`);
      const res = await this.prismaService.account.findFirst({
        where: {
          isDelete: false
        }
      })
      return res
    } catch (error) {
      handleError(this.logger, error, {
        common: '获取存储信息字段失败'
      })
    }

  }


}
